/**
 * Project Name: meatball-dowload-logs
 * Package Name: com.meatball.controller
 * File Name: DownloadController
 * Date: 2021/2/2 22:35
 * User: 張翔宇
 * Copyright (c) 2021, zhang.xiangyu@foxmail.com All Rights Reserved.
 */
package com.meatball.controller;

import com.meatball.service.DownloadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 *
 * @title: DownloadController.java
 * @author: 張翔宇
 * @date: 2021/2/2 22:35
 * @version: V3.0
 */
@RestController
@CrossOrigin
@RequestMapping("/logs")
public class DownloadController {
    @Autowired
    private DownloadService service;

    @GetMapping("/files/{directory}/{ip}")
    public List<String> getFiles(@PathVariable String directory, @PathVariable String ip) throws Exception {
        return service.getDirectory(directory, ip);
    }

    @GetMapping("/download/{name}/{directory}/{ip}")
    public void download(@PathVariable String name, @PathVariable String directory, @PathVariable String ip) throws Exception {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        // 设置信息给客户端不解析
        String type = new MimetypesFileTypeMap().getContentType(name);
        // 设置ContentType，即告诉客户端所发送的数据属于什么类型
        response.setHeader("Content-type",type);
        // 设置编码
        String newName = directory + "_" + ip + "_" + name;
        String encode = new String(newName.getBytes("utf-8"), "iso-8859-1");
        // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
        response.setHeader("Content-Disposition", "attachment;filename=" + encode);
        service.download(name, directory, ip, response);
    }
}